package com.doubao.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;

@Slf4j
public class JsonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 对象转JSON字符串
     */
    public static String objectToJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON字符串异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * JSON字符串转对象
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (Exception e) {
            log.error("JSON字符串转对象异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * JSON字符串转List
     */
    public static <T> List<T> jsonToList(String json, Class<T> clazz) {
        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, clazz);
            return MAPPER.readValue(json, javaType);
        } catch (Exception e) {
            log.error("JSON字符串转List异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * JSON字符串转Map
     */
    public static <K, V> Map<K, V> jsonToMap(String json, Class<K> keyClass, Class<V> valueClass) {
        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(Map.class, keyClass, valueClass);
            return MAPPER.readValue(json, javaType);
        } catch (Exception e) {
            log.error("JSON字符串转Map异常: {}", e.getMessage(), e);
            return null;
        }
    }
}